package com.m1.tzolkin.model.log;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

public class Log implements ILog {
	
	// ATTRIBUTS
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -5405219059421138209L;
	private final List<String[]> sentences;
	private Locale locale;
	private final PropertyChangeSupport listeners;
	
	// CONSTRUCTEUR
	
	public Log() {
		sentences = new ArrayList<String[]>();
		locale = new Locale("en", "US");
		listeners = new PropertyChangeSupport(this);
	}
	
	// REQUETES
	
	@Override
	public PropertyChangeListener[] getPropertyChangeListeners() {
		return listeners.getPropertyChangeListeners();
	}
	
	@Override
	public String getLastVerbalSentence() {
		return getVerbal(sentences.get(sentences.size() - 1), ResourceBundle.getBundle("keywords", locale));
	}

	@Override
	public List<String> getVerbalSentences() {
		ResourceBundle bundle = ResourceBundle.getBundle("keywords", locale);
		List<String> l = new ArrayList<String>();
		for (String[] s : sentences) {
			l.add(getVerbal(s, bundle));
		}
		return l;
	}
	
	// COMMANDES
	
	@Override
	public void addPropertyChangeListener(PropertyChangeListener l) {
		listeners.addPropertyChangeListener(l);
	}
	
	@Override
	public void removePropertyChangeListener(PropertyChangeListener l) {
		listeners.removePropertyChangeListener(l);
	}

	@Override
	public void addSentence(String[] s) {
		String old = null;
		if (sentences.size() > 0) {
			old = getLastVerbalSentence();
		}
		sentences.add(s);
		listeners.firePropertyChange("messages", old, getLastVerbalSentence());
	}
	
	@Override
	public void setLocale(Locale l) {
		locale = l;
	}
	
	public static String getTranslation(Locale l, String[] str) {
		ResourceBundle messages = ResourceBundle.getBundle("keywords", l);
		StringBuffer sb = new StringBuffer();
		for (String s : str) {
			if (!sb.equals("")) sb.append(" ");
			if (isIn(messages, s)) {
				sb.append(messages.getString(s));
			} else {
				sb.append(s);
			}
		}
		return sb.toString();
	}
	
	// OUTILS
	
	private static boolean isIn(ResourceBundle r, String key) {
		Enumeration<String> e = r.getKeys();
		while (e.hasMoreElements()) {
			if (e.nextElement().equals(key)) {
				return true;
			}
		}
		return false;
	}
	
	private String getVerbal(String[] str, ResourceBundle bundle) {
		StringBuffer sb = new StringBuffer();;
		for (String s : str) {
			if (!sb.equals("")) sb.append(" ");
			try {
				sb.append(bundle.getString(s));
			} catch (MissingResourceException e) {
				sb.append(s);
			}
		}
		return sb.toString();
	}

}
